package com.wanyangproject.my;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.activity.TieZiXiangQingActivity;
import com.wanyangproject.entity.MyTieZiLieBiaoEntity;
import com.wanyangproject.entity.ShouYeZhaoPinXiangQingEntity;
import com.wanyangproject.entity.TieZiShouCangEntity;
import com.wanyangproject.entity.ZhanPinLieBiaoEntity;
import com.wanyangproject.entity.ZhaoPinFenXiangEntity;
import com.wanyangproject.entity.ZhaoPinShouCangEntity;
import com.wanyangproject.myadapter.MyZhaoPinAdapter;
import com.wanyangproject.popuwindow.SharePopupWindow;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.WebViewUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ZhaoPinXiangQingActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.image_zhuanfa)
    ImageView imageZhuanfa;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_fabu_shijian)
    TextView tvFabuShijian;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_yaoqiu)
    TextView tvYaoqiu;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_fuli)
    TextView tvFuli;
    @BindView(R.id.tv_company_address)
    TextView tvCompanyAddress;
    @BindView(R.id.tv_company_guimo)
    TextView tvCompanyGuimo;
    @BindView(R.id.tv_company_hangye)
    TextView tvCompanyHangye;
    @BindView(R.id.relative_phone)
    RelativeLayout relativePhone;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.image_shoucang)
    ImageView imageShoucang;
    private String zhaopinid;
    private WebSettings mWebSettings;
    private String content;
    private ShouYeZhaoPinXiangQingEntity shouYeZhaoPinXiangQingEntity;
    private SharePopupWindow sharePopupWindow;
    private ProgressDialog progressDialog;
    private static Boolean isOK = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhao_pin_xiang_qing);
        ButterKnife.bind(this);


        mWebSettings = webView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);  //允许加载javascript
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        mWebSettings.setSupportZoom(false);     //允许缩放
        mWebSettings.setBuiltInZoomControls(false); //原网页基础上缩放
        mWebSettings.setUseWideViewPort(false);   //任意比例缩放
//        mWebSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
//        mWebSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        mWebSettings.setTextSize(WebSettings.TextSize.NORMAL);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE,null);//开启硬件加速




        Intent intent = getIntent();
        zhaopinid = intent.getStringExtra("zhaopinid");
        System.out.println(zhaopinid + "         招聘详情接收的招聘id");


        if (zhaopinid != null) {
            //        招聘详情的网络请求
            initZhaoPinXiangQingHttp();
        }


        //        招聘收藏列表的网络请求
        initZhaoPinShouCangHttp();

        initView();
    }




    //    招聘信息分享的网络请求
    private void initFenXiang() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "zhaopin/getShareInfo")
                .addHeader("token", ContractUtils.getTOKEN(ZhaoPinXiangQingActivity.this))
                .addParams("id", zhaopinid)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(ZhaoPinXiangQingActivity.this, response);
                        System.out.println(response + "             招聘信息分享的网络请求");

                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            ZhaoPinFenXiangEntity zhaoPinFenXiangEntity = gson.fromJson(response, ZhaoPinFenXiangEntity.class);
                            Object itemsOnClick = null;
                            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.loginbaibian);
                            sharePopupWindow = new SharePopupWindow(ZhaoPinXiangQingActivity.this, (View.OnClickListener) itemsOnClick, zhaoPinFenXiangEntity.getResponse().getTitle(), zhaoPinFenXiangEntity.getResponse().getUrl(), bitmap);
                            sharePopupWindow.showAtLocation(findViewById(R.id.relative_Layout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//                            ChuanZhiEntity.fenxiang = zhaoPinFenXiangEntity.getResponse();//传值
                        }else {
                            ContractUtils.Code400(ZhaoPinXiangQingActivity.this,response);
                        }
                    }
                });
    }


    private void initView() {
        webView.setWebViewClient(new WebViewClient() {
            /**
             * 拦截 url 跳转,在里边添加点击链接跳转或者操作
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return WebViewUtils.shouldOverrideUrlLoading(view, request, ZhaoPinXiangQingActivity.this);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                System.out.println("66666666666666666666");
                return WebViewUtils.shouldOverrideUrlLoading(view, url, ZhaoPinXiangQingActivity.this);

            }


            /**
             * 在开始加载网页时会回调
             */
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                System.out.println("111111111111111111");
            }

            /**
             * 加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
             */
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

            }


            /**
             * 在结束加载网页时会回调
             */
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("chenggongchenggongchenggong");
                if(progressDialog != null){
                    progressDialog.dismiss();
                }

            }

            /**
             * 当接收到https错误时，会回调此函数，在其中可以做错误处理
             */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            /**
             * 在每一次请求资源时，都会通过这个函数来回调
             */
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return null;
            }

            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);
                if(progressDialog != null){
                    progressDialog.dismiss();
                }
            }
        });
    }


    //    招聘详情的网络请求
    private void initZhaoPinXiangQingHttp() {
        progressDialog = new ProgressDialog(ZhaoPinXiangQingActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "zhaopin/getDetail")
                .addHeader("token", ContractUtils.getTOKEN(ZhaoPinXiangQingActivity.this))
                .addParams("id", zhaopinid)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e+"            eeeeeeee 招聘详情");
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(ZhaoPinXiangQingActivity.this, response);
                        System.out.println(response + "             招聘详情的网络请求");

                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            shouYeZhaoPinXiangQingEntity = gson.fromJson(response, ShouYeZhaoPinXiangQingEntity.class);
                            if (shouYeZhaoPinXiangQingEntity.getResponse().getData().getContent() == null) {

                            } else {
                                //                            职位描述内容
                                content = shouYeZhaoPinXiangQingEntity.getResponse().getData().getContent();
                                String newContent = content;
                                if(!newContent.endsWith("</p>")){
                                    newContent = newContent + "</p>";
                                }
                                webView.loadDataWithBaseURL("http://www.baidu.com", "<style>* {font-size:14px;line-height:20px;}p {color:#666666;}</style>"+newContent, "text/html", "UTF-8", null);
//                                webView.loadDataWithBaseURL("http://www.baidu.com", "<style>* {font-size:14px;line-height:20px;}p {color:#666666;}a {color:#666666;}</style>"+getNewContent(content), "text/html", "UTF-8", null);
                            }


//
                            if(shouYeZhaoPinXiangQingEntity.getResponse().getData().getSeeNums() == null){

                            }else{
                                tvNumber.setText("浏览："+shouYeZhaoPinXiangQingEntity.getResponse().getData().getSeeNums()+"人");
                            }





                            if (shouYeZhaoPinXiangQingEntity.getResponse().getData().getTitle() == null) {

                            } else { //  标题
                                tvTitle.setText(shouYeZhaoPinXiangQingEntity.getResponse().getData().getTitle());
                            }

                            if (shouYeZhaoPinXiangQingEntity.getResponse().getData().getMoney() == null) {

                            } else { // 薪资
                                tvMoney.setText(shouYeZhaoPinXiangQingEntity.getResponse().getData().getMoney());
                            }

                            if (shouYeZhaoPinXiangQingEntity.getResponse().getData().getAdd_time() == null) {

                            } else { //发布时间
                                tvFabuShijian.setText("发布时间：" + shouYeZhaoPinXiangQingEntity.getResponse().getData().getAdd_time());
                            }


                            if (shouYeZhaoPinXiangQingEntity.getResponse().getData().getYaoqiu() == null) {

                            } else {  // 要求
                                tvYaoqiu.setText("要求：" + shouYeZhaoPinXiangQingEntity.getResponse().getData().getYaoqiu());
                            }


                            if (shouYeZhaoPinXiangQingEntity.getResponse().getData().getAddress() == null) {

                            } else {
                                tvAddress.setText("地区：" + shouYeZhaoPinXiangQingEntity.getResponse().getData().getAddress());
                            }


                            if (shouYeZhaoPinXiangQingEntity.getResponse().getData().getFuli() == null) {

                            } else {
                                tvFuli.setText("福利：" + shouYeZhaoPinXiangQingEntity.getResponse().getData().getFuli());
                            }


                            if (shouYeZhaoPinXiangQingEntity.getResponse().getEnterInfo().getInfo().getAddress() == null) {

                            } else {
                                tvCompanyAddress.setText("地区：" + shouYeZhaoPinXiangQingEntity.getResponse().getEnterInfo().getInfo().getAddress());
                            }


                            if (shouYeZhaoPinXiangQingEntity.getResponse().getEnterInfo().getInfo().getGuimo() == null) {

                            } else {
                                tvCompanyGuimo.setText("规模：" + shouYeZhaoPinXiangQingEntity.getResponse().getEnterInfo().getInfo().getGuimo());
                            }


                            if (shouYeZhaoPinXiangQingEntity.getResponse().getEnterInfo().getInfo().getHangye() == null) {

                            } else {
                                tvCompanyHangye.setText("行业：" + shouYeZhaoPinXiangQingEntity.getResponse().getEnterInfo().getInfo().getHangye());
                            }


                        }

                    }
                });
    }

    @OnClick({R.id.image_back, R.id.image_zhuanfa, R.id.image_shoucang,R.id.tv_title, R.id.tv_money, R.id.tv_fabu_shijian, R.id.tv_number, R.id.tv_yaoqiu, R.id.tv_address, R.id.tv_fuli, R.id.tv_company_address, R.id.tv_company_guimo, R.id.tv_company_hangye, R.id.relative_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
//            分享
            case R.id.image_zhuanfa:

//        招聘信息分享的网络请求
                initFenXiang();
                break;
//            收藏
            case R.id.image_shoucang:
//                收藏的网络请求
                initShouCangHttp();
                break;
            case R.id.tv_title:
                break;
            case R.id.tv_money:
                break;
            case R.id.tv_fabu_shijian:
                break;
            case R.id.tv_number:
                break;
            case R.id.tv_yaoqiu:
                break;
            case R.id.tv_address:
                break;
            case R.id.tv_fuli:
                break;
            case R.id.tv_company_address:
                break;
            case R.id.tv_company_guimo:
                break;
            case R.id.tv_company_hangye:
                break;
            case R.id.relative_phone:
//                打电话累计的接口的网络请求
                initDaDianHuaLeiJiHttP();

//                判断当前SDK版本号
                if (Build.VERSION.SDK_INT >= 23) {
//                    当前拨打电话权限是没有给的
                    if (ContextCompat.checkSelfPermission(ZhaoPinXiangQingActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
//                        我要请求权限
                        ActivityCompat.requestPermissions(ZhaoPinXiangQingActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
                    } else {
                        call();
                    }
                } else {
                    call();
                }
                break;
        }
    }






//    收藏
    private void initShouCangHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"zhaopin/shoucang")
                .addHeader("token",ContractUtils.getTOKEN(ZhaoPinXiangQingActivity.this))
                .addParams("id",zhaopinid)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response+"            收藏招聘");
                        ContractUtils.Code500(ZhaoPinXiangQingActivity.this,response);
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            TieZiShouCangEntity tieZiShouCangEntity = gson.fromJson(response, TieZiShouCangEntity.class);
                            Toast.makeText(ZhaoPinXiangQingActivity.this, tieZiShouCangEntity.getMsg(), Toast.LENGTH_SHORT).show();
                            if(tieZiShouCangEntity.getMsg().equals("收藏成功！")){
                                imageShoucang.setImageResource(R.drawable.quxia_shoucang);
                            }else if(tieZiShouCangEntity.getMsg().equals("取消收藏成功！")){
                                imageShoucang.setImageResource(R.drawable.shoucang_white);
                            }
                        }
                    }
                });
    }





    //    招聘收藏列表的网络请求
    private void initZhaoPinShouCangHttp() {
        final ProgressDialog progressDialog = new ProgressDialog(ZhaoPinXiangQingActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"zhaopin/myshoucang")
                .addHeader("token",ContractUtils.getTOKEN(ZhaoPinXiangQingActivity.this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressDialog.dismiss();
                        System.out.println(response+"           招聘收藏列表的网络请求");
                        ContractUtils.Code500(ZhaoPinXiangQingActivity.this,response);
                        if(response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            ZhanPinLieBiaoEntity zhanPinLieBiaoEntity = gson.fromJson(response, ZhanPinLieBiaoEntity.class);

                            Boolean isOK = false;
                            for (int i = 0; i < zhanPinLieBiaoEntity.getResponse().size(); i++) {
                                ZhanPinLieBiaoEntity.ResponseBean responseBean = zhanPinLieBiaoEntity.getResponse().get(i);
                                if(responseBean.getId().equals(zhaopinid)){
                                    isOK = true;
                                }
                            }

                            if(isOK == true){
                                imageShoucang.setImageResource(R.drawable.quxia_shoucang);
                            }



//                            try {
//                                JSONObject jsonObject = new JSONObject(response);
//                                JSONArray response1 = jsonObject.getJSONArray("response");
//
//                                Boolean isOK = false;
//                                if(response1 != null){
//                                    for (int i = 0; i < response1.length(); i++) {
//                                        JSONObject json = (JSONObject) response1.get(i);
//                                        if(json.getString("0").equals(zhaopinid)){
//                                            isOK = true;
//                                        }
//                                    }
//
//                                    if(isOK == true){
//                                        imageShoucang.setImageResource(R.drawable.quxia_shoucang);
//                                    }
//
//                                }
//
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }

                        }
                    }
                });
    }









    //    打电话累计的网络请求
    private void initDaDianHuaLeiJiHttP() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "zhaopin/callNums")
                .addHeader("token", ContractUtils.getTOKEN(ZhaoPinXiangQingActivity.this))
                .addParams("id", zhaopinid)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(ZhaoPinXiangQingActivity.this, response);
                        System.out.println(response + "     打电话累计的网络请求");
                    }
                });
    }

    public void call() {
        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + shouYeZhaoPinXiangQingEntity.getResponse().getData().getPhone()));
            startActivity(intent);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (permissions.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    call();
                } else {
                    Toast.makeText(ZhaoPinXiangQingActivity.this, "您拒绝拨打电话", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }


    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    public static String getNewContent(String htmltext) {

//
//        if(isOK == false){
//            return htmltext;
//        }
//
//        isOK = true;
        try {
            Document doc = Jsoup.parse(htmltext);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }

            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }

}
